package ms.mall.controller;

import ms.common.exception.BizException;
import ms.common.util.string.StringUtil;
import ms.mall.bean.CartParamBean;
import ms.mall.config.ResponseCode;
import ms.mall.entity.Cart;
import ms.mall.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Project Name: ms
 * File Name: CartController
 * Package Name: ms.mall.controller
 * Date: 2018/6/4  16:37
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 加入购物车
     * @param cartParamBean
     */
    @PostMapping(value = "/create")
    public void create(@RequestBody CartParamBean cartParamBean) {
        checkParam(cartParamBean);
        cartService.create(cartParamBean);
    }

    /**
     * 修改购物车
     * @param cartParamBean
     */
    @PostMapping(value = "/update")
    public void update(@RequestBody CartParamBean cartParamBean) {
        checkParam(cartParamBean);
        cartService.update(cartParamBean);
    }

    /**
     * 删除购物车
     * @param cartParamBean
     */
    @PostMapping(value = "/del")
    public void del(@RequestBody CartParamBean cartParamBean) {
        cartService.del(cartParamBean);
    }

    /**
     * 购物车列表
     * @param cartParamBean
     */
    @PostMapping(value = "/list")
    public List<Cart> list(@RequestBody CartParamBean cartParamBean) {
        return cartService.list(cartParamBean);
    }


    /**
     * 校验参数
     * @param cartParamBean
     */
    private void checkParam(CartParamBean cartParamBean) {
        if(StringUtil.isEmpty(cartParamBean.getGoodId())) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "商品信息不能为空");
        }
        if(StringUtil.isEmpty(cartParamBean.getSkuId())) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "分类信息不能为空");
        }
        if(StringUtil.isEmpty(cartParamBean.getName())) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "名称不能为空");
        }
        if(StringUtil.isEmpty(cartParamBean.getPrice())) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "价格不能为空");
        }
        if(StringUtil.isEmpty(cartParamBean.getNum())) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "数量不能为空");
        }
    }
}
